<template>
  <div class="uni-table-form">
    <el-card shadow="never" class="aui-card--fill" v-loading="loading">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane :label="dataList1Lable" name="1">
          <CpnData1 @dataUpdate="dataUpdate1"></CpnData1>
        </el-tab-pane>
        <el-tab-pane :label="dataList2Lable" name="2">
          <CpnData2 @dataUpdate="dataUpdate2"></CpnData2>
        </el-tab-pane>
      </el-tabs>
      <div style="padding-right: 20px;padding-bottom: 50px;">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'">
          <el-row>
            <el-col :span="24">
              <el-form-item label="比对条件" prop="comparisonCondition">
                <!-- multiple collapse-tags  -->
                <!-- <el-select v-model="dataForm.comparisonCondition" multiple placeholder="请选择">
                  <el-option v-for="item in this.aaaaa" :key="item.val" :label="item.label" :value="item.val">
                  </el-option>
                </el-select> -->
                <el-select v-model="value1" multiple placeholder="请选择" style="width: 100%;">
                  <el-option v-for="item in fieldDatas" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>

                <!-- <el-input v-model.number="dataForm.comparisonCondition" placeholder="比对条件" clearable></el-input> -->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="比对字段" prop="comparisonField">

                <el-select v-model="value2" multiple placeholder="请选择" style="width: 100%;">
                  <el-option v-for="item in fieldDatas" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
                <!-- <el-input v-model.number="dataForm.comparisonField" placeholder="比对字段" clearable></el-input> -->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="显示字段" prop="showField">
                <!-- <el-input v-model.number="dataForm.showField" placeholder="显示字段" clearable></el-input> -->
                <el-select v-model="value3" multiple placeholder="请选择" style="width: 100%;">
                  <el-option v-for="item in fieldDatas" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="24" style="text-align:center">
            <el-button :disabled="loading" size="small" type="primary" @click="dataFormSubmitHandle()">开始比对</el-button>
            <el-button :disabled="loading" v-if="dataForm.comparisonDate" size="small" type="warning" @click="openResult()">查看上次比对结果</el-button>
            <!-- <el-button size="small" @click="closeTab()">{{ $t('close') }}</el-button> -->
          </el-col>
        </el-form>
      </div>
    </el-card>
  </div>
</template>
<script>
import CpnData1 from './cpnData1'
import CpnData2 from './cpnData2'
import debounce from 'lodash/debounce'
import { moduleRoutes } from '@/router'

export default {
  data () {
    return {
      loading: true,
      activeName: '1',
      name: '',
      dataList1Size: 0,
      dataList1Data: [],
      dataList1Lable: '数据源1（未导入）',
      dataList2Size: 0,
      dataList2Lable: '数据源2（未导入）',
      dataList2Data: [],
      dataForm: {
        id: '',
        // name: '',
        comparisonCondition: '',
        comparisonField: '',
        showField: ''
      },
      value1: [],
      value2: [],
      value3: []

    }
  },
  computed: {
    fieldDatas () {
      let fieldDatas = []
      let l1 = this.getFieldLength(this.dataList1Data)
      let l2 = this.getFieldLength(this.dataList2Data)
      let l = l1 > l2 ? l1 : l2
      for (let index = 0; index < l; index++) {
        let field = {
          label: '字段' + (index + 1),
          value: 'f' + (index + 1)
        }
        fieldDatas.push(field)
      }
      console.debug('fieldDatas', fieldDatas)
      return fieldDatas
    },
    dataRule () {
      return {
        comparisonCondition: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        comparisonField: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
        // showField: [
        //   { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        // ]
      }
    }
  },
  components: {
    CpnData1,
    CpnData2
  },
  watch: {
    'value1': function (val) {
      if (val && val.length) {
        this.dataForm.comparisonCondition = val.join(',')
      } else {
        this.dataForm.comparisonCondition = ''
      }
    },
    'value2': function (val) {
      if (val && val.length) {
        this.dataForm.comparisonField = val.join(',')
      } else {
        this.dataForm.comparisonCondition = ''
      }
    },
    'value3': function (val) {
      if (val && val.length) {
        this.dataForm.showField = val.join(',')
      } else {
        this.dataForm.showField = ''
      }
    }
  },
  created () {
    this.$nextTick(() => {
      if (this.$route.params.themeId) {
        this.dataForm.id = this.$route.params.themeId
        this.name = this.$route.params.name
        // console.debug('1', this.dataForm)
        this.getInfo()
      }
    })
  },
  methods: {
    getFieldLength (datas) {
      let fMaxField = 0
      for (const data of datas) {
        let fsize = 0
        for (let i in data) {
          // console.debug('1', i)
          if (i.substr(0, 1) !== 'f') {
            continue
          }
          if (data[i]) {
            fsize++
          }
        }
        if (fsize > fMaxField) {
          fMaxField = fsize
        }
      }
      return fMaxField
    },
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.loading = true
          this.getInfo()
        }
      })
    },
    dataUpdate1 (val) {
      // this.getField(val)
      // this.fieldDatas()
      this.dataList1Data = val
      let length = val.length
      this.dataList1Size = length
      if (length) {
        this.dataList1Lable = `数据源1（${length}）`
      } else {
        this.dataList1Lable = '数据源1（未导入）'
      }
    },
    dataUpdate2 (val) {
      this.dataList2Data = val
      let length = val.length
      this.dataList2Size = length
      if (length) {
        this.dataList2Lable = `数据源2（${length}）`
      } else {
        this.dataList2Lable = '数据源2（未导入）'
      }
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/cpn/cpnTheme/${this.dataForm.id}`).then(({ data: res }) => {
        this.loading = false
        if (res.code !== 0) {
          return false
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        if (this.dataForm.comparisonCondition) {
          this.value1 = this.dataForm.comparisonCondition.split(',')
        }
        if (this.dataForm.comparisonField) {
          this.value2 = this.dataForm.comparisonField.split(',')
        }
        if (this.dataForm.showField) {
          this.value3 = this.dataForm.showField.split(',')
        }
      }).catch(() => { })
    },
    // 新增 / 修改
    openResult () {
      var title = '查看比对结果-' + this.name
      var id = this.dataForm.id
      // if (row && row.id) {
      //   // title = '编辑代码模板--' + row.templateName + '(' + row.templateCode + ')'
      //   id = row.id
      // }
      // 打开路由
      var router = {
        name: 'cpnResult',
        id: id,
        menuId: this.$route.meta.menuId,
        oldName: 'cpn-cpnTheme1',
        path: 'cpn/cpnResult',
        title: title
      }
      var params = {
        themeId: id,
        timestamp: this.$xeutils.timestamp()
      }
      this.openNewTab(this.$router, router, params)
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      if (!this.dataList1Size) {
        this.activeName = '1'
        return this.$message.error('请导入数据源1数据')
      }
      if (!this.dataList2Size) {
        this.activeName = '2'
        return this.$message.error('请导入数据源2数据')
      }

      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.loading = true

        this.$http[!this.dataForm.id ? 'post' : 'put']('/cpn/cpnTheme/', this.dataForm).then(({ data: res }) => {
          // this.loading = false
          if (res.code !== 0) {
            this.loading = false
            return false
          }
          // this.loading = false

          // this.openResult()

          this.$http.post('/cpn/cpnResult/comparsion', { themeId: this.dataForm.id })
            .then(({ data: res }) => {
              this.loading = false
              this.openResult()
            })

          // this.$message({
          //   message: this.$t('prompt.success'),
          //   type: 'success',
          //   duration: 500,
          //   onClose: () => {
          //     this.visible = false
          //     // this.$emit('refreshDataList')
          //   }
          // })
        }).catch(() => {
          this.loading = false
        })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    /**
     *
     * @param router {name:新路由,id:业务id,oldName:当前页路由,path:打开页面的路径,title:tabTitle}
     * @param params {} 路由参数
     * @returns {*|number}
     */
    openNewTab ($router, router, params) {
      // 组装路由名称, 并判断是否已添加, 如是: 则直接跳转
      var routeName = router.name + `__` + router.id
      var route
      if (router.children && router.children.length > 0) {
        var childName = router.children[0].name
        route = window.SITE_CONFIG['dynamicRoutes'].filter(
          (item) => item.name === childName
        )[0]
        if (route) {
          return $router.push({ name: childName, params: params })
        }
      } else {
        route = window.SITE_CONFIG['dynamicRoutes'].filter(
          (item) => item.name === routeName
        )[0]
        if (route) {
          // console.log('1', routeName)
          return $router.push({ name: routeName, params: params })
        }
      }

      // 否则: 添加并全局变量保存, 再跳转
      route = {
        path: router.oldName + `__` + router.id,
        component: () => import(`@/views/modules/${router.path}`),
        name: routeName,
        meta: {
          ...window.SITE_CONFIG['contentTabDefault'],
          menuId: router.menuId,
          isTab: true,
          title: '' + router.title
        },
        children: router.children
      }
      $router.addRoutes([
        {
          ...moduleRoutes,
          name: `main-dynamic__${router.name}`,
          children: [route]
        }
      ])
      window.SITE_CONFIG['dynamicRoutes'].push(route)
      if (router.children && router.children.length > 0) {
        $router.push({ name: router.children[0].name, params: params })
      } else {
        $router.push({ name: route.name, params: params })
        console.log(2, route.name)
      }
    }
  }
}
</script>
<style lang="scss">
.uni-table-form {
  .el-card__body,
  .el-main {
    padding: 0px;
  }
  .el-tabs--card > .el-tabs__header .el-tabs__nav {
    transform: translateX(0px);
    border-top-width: 0px;
    border-left-width: 0px;
    border-radius: 0;
  }
  .el-tabs__content {
    padding: 20px;
    padding-top: 0px;
  }
}
</style>
